<?php
// 应用公共文件
function setPassword($password): array
{
    $token = \think\helper\Str::random(32, 9);
    $password = password_hash($token . $password . $token, PASSWORD_DEFAULT);
    return compact('password', 'token');
}

function checkPassword($password, $token, $hash): bool
{
    return password_verify($token . $password . $token, $hash);
}

function setCacheToken($prefix = "admin"): string
{
    $token = \think\helper\Str::random(32, 9);
    if (\think\facade\Cache::has("{$prefix}_$token")) {
        setCacheToken($prefix);
    }
    return $token;
}

function pageData($data): array
{
    if (is_object($data)) $data = $data->toArray();
    return [
        "list" => $data['data'],
        "total" => $data['total'],
        "last_page" => $data['last_page']
    ];
}

function setOrderSn($prefix = "O"): string
{
    $order = date("YmdHis") . \think\helper\Str::random(8, 1);
    return $prefix . $order;
}

function excelData($data)
{
    return [
        "result" => $data['result'] ?? [],
        "last_page" => $data['last_page'] ?? 1,
        "file" => $data['file'] ?? "导出文件",
        "title" => $data['title'] ?? [$data['file']],
        "header" => $data['header'] ?? [],
        "merge" => $data['merge'] ?? []
    ];
}

function mathLitter($money, $type, $gun_price): float|int
{
    $litter = bcdiv($money, $gun_price, 4);
    return match ($type) {
        2 => ceil(bcmul($litter, 100, 0)) / 100,
        3 => floor(bcmul($litter, 100, 0)) / 100,
        4 => round($litter, 2, PHP_ROUND_HALF_DOWN),
        5 => round(ceil($litter * 1000) / 1000, 2, PHP_ROUND_HALF_DOWN),
        default => round($litter, 2),
    };
}

function mathSettMoney($litter, $money, $sett_type, $sett_money, $discount, $price, $number): float|int
{
    if ($discount == 0) return $money;
//    dd($number);
    if ($number == 2) {
        $rate = bcdiv($number, 100, 4);
        $discount = round($price * $rate, 2);
    }
    $total = match ($sett_type) {
        2 => bcmul($litter, bcsub($price, $discount, 2), 4),
        default => bcsub($money, bcmul($litter, $discount, 4), 4)
    };
    return match ($sett_money) {
        2 => round($total, 2, PHP_ROUND_HALF_DOWN),
        3 => floor($total * 100) / 100,
        default => round($total, 2)
    };
}

function mathDiscount($type, $rate, $gun_price)
{
    if ($rate <= 0) return $gun_price;
    if ($type == 2) {
        $out = 1 - bcdiv($rate, 100, 4);
        $discount_money = round($gun_price * $out, 2);
    } else {
        $discount_money = bcsub($gun_price, $rate, 2);
    }
    return $discount_money;
}

function mathSupplierDiscount($station, $oil, $supplier, $money): array
{
    //首先计算油站返利优惠金额
    $prices = ["sat_price", "mon_price", "tue_price", "wed_price", "thu_price", "fri_price", "sat_price"][date("w")];
    $oil_price = $oil[$prices] > 0 ? $oil[$prices] : $oil['default_price'];
    $unit = $oil['rate_unit'];
    $discount = mathDiscount($unit, $oil_price, $oil['gun_price']);
    $def_rate = $supplier["$oil[oil]_rate"] ?? 0;
    $rate = bcdiv($def_rate, 100, 6);
    if ($rate > 0) {
        $discount = round($discount * (1 - $rate), 2);
    } elseif ($rate < 0) {
        //原始的优惠数
        if ($unit == 2) {
            $discount = round($oil['gun_price'] * (1 - (bcdiv($oil_price, 100, 4) + $rate)), 4);
        } else {
            $rate = abs($rate);
            $dis = round($oil['gun_price'] * $rate, 6);
            $discount = round($oil['gun_price'] - $oil_price - $dis, 4);
        }
    }
//    //计算加油数量
    $litter = mathLitter($money, $station['litter_type'], $oil['gun_price']);
    $discount_money = $discount != $oil['gun_price'] ? round($litter * $discount, 2) : $money;
    $discount = (float)bcsub($money, $discount_money, 2);
    $ser_money = 0;
    //判断是否有服务费
    if ($station['ser_price'] > 0) {
        $ser_price = bcdiv($station['ser_price'], 100, 4);
        $ser_money = rountd($money * $ser_price, 2);
        $discount_money = round($discount_money * $ser_money, 2);
    }
    return compact("discount", "litter", "discount_money", "money", "ser_money");
}

function station_qrcode($name, $code): string
{
//    $code = request()->param('code');
    $dir = "./upload/qrcode/station/";
    if (!file_exists($dir . $code . ".jpg")) {
        if (!file_exists($dir))
            mkdir($dir, 0777, true);
        //生成二维码
        $qrcode = app(\app\Qrcode::class);
        $_code = $qrcode->createQrcode("https://gas-test.zhissf.com/qr_station?code=$code", 220);
        $label = $qrcode->createLabel($name);
        $qrcode->jpg("station", $code, $_code, null, $label);
    }
    return request()->domain() . "/upload/qrcode/station/$code.jpg";
}

function push_notice($url, $data)
{
    $client = new \GuzzleHttp\Client([
        "verify" => false,
        "headers" => ["content-type" => "application/json;charset=utf-8"],
        "base_uri" => $url,
    ]);
    $log = app(\app\Log::class, ['dir' => 'push_order']);
    try {
        $res = $client->request("POST", "", [
            "json" => $data
        ]);
        $content = $res->getBody()->getContents();
        $log->write(['content' => $content, 'param' => $data]);
        return json_decode($content, true);
    } catch (\Exception $e) {
        $log->write(['error' => $e->getMessage()]);
        return false;
    }
}
